package com.twetec.cms.service.ucenter.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twetec.cms.common.constant.RedisConst;
import com.twetec.cms.common.util.aes.AESUtils;
import com.twetec.cms.common.util.cache.RedisCache;
import com.twetec.cms.dao.mapper.system.CmsMenuMapper;
import com.twetec.cms.dao.mapper.system.CmsRoleMenuMapper;
import com.twetec.cms.dao.mapper.system.CmsUserRoleMapper;
import com.twetec.cms.model.po.system.CmsMenuPO;
import com.twetec.cms.model.po.system.CmsRoleMenuPO;
import com.twetec.cms.model.po.system.CmsUserRolePO;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.vo.ucenter.UserVO;
import com.twetec.cms.service.ucenter.UserService;
import com.xxg.base.module.Operater;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.twetec.cms.dao.mapper.ucenter.UserMapper;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhxl
 * @since 2020-10-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private CmsUserRoleMapper cmsUserRoleMapper;



    @Autowired
    private CmsMenuMapper cmsMenuMapper;


    /**
     * 添加权限菜单到redis中
     * @param userId
     * @return
     */
    @Override
    public void addPermissionMenuListInRedis(Long userId) {
        // 查询用户和角色关联表
        QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();
        cmsUserRolePOQueryWrapper.lambda().eq(CmsUserRolePO::getUserId, userId);
        List<CmsUserRolePO> cmsUserRolePOS = cmsUserRoleMapper.selectList(cmsUserRolePOQueryWrapper);
        if (null == cmsUserRolePOS || cmsUserRolePOS.isEmpty()) return ;

        // 获取角色id
        ArrayList<Long> roleList = new ArrayList<>();
        for (CmsUserRolePO cmsUserRolePO : cmsUserRolePOS) {
            roleList.add(cmsUserRolePO.getRoleId());
        }

        QueryWrapper cmsMenuPOQueryWrapper = new QueryWrapper<>();
        cmsMenuPOQueryWrapper.in("CMS_ROLE_MENU.ROLE_ID", roleList);
        List<CmsMenuPO> cmsMenuPOS = cmsMenuMapper.selectRoleMenu(cmsMenuPOQueryWrapper);

        // 缓存到redis中的权限集合
        ArrayList<String> permissionMenuList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        for (CmsMenuPO cmsMenuPO : cmsMenuPOS) {
            // 站点id + 栏目id + 权限标识
            stringBuffer.append(cmsMenuPO.getSiteId()).append(":");
            if (null == cmsMenuPO.getColumnId()) {
                stringBuffer.append(0);
            } else {
                stringBuffer.append(cmsMenuPO.getColumnId());
            }

            if (null != cmsMenuPO.getPermission()) {
                stringBuffer.append(":");
                stringBuffer.append(cmsMenuPO.getPermission());
            }
            permissionMenuList.add(stringBuffer.toString());
            // 清空内容
            stringBuffer.delete(0,stringBuffer.length());
        }

        String key = RedisConst.REDISKEY_PERMISSION_MENU + userId;
        boolean setList = redisCache.setList(key, permissionMenuList);
//        redisTemplate.boundValueOps( key).set(permissionMenuList);
        return ;
    }

    @Override
    public List<Object> getPermissionMenuListFromRedis(Long userId) {
        String key = RedisConst.REDISKEY_PERMISSION_MENU + userId;
        List<Object> list = redisCache.getList(key);
        // 如果没有拿到，或者拿到的是空则先添加后返回
        if (null == list || list.size() == 0) {
            addPermissionMenuListInRedis(userId);
            list = redisCache.getList(key);
        }
        return list;
    }


    @Override
    public boolean create(String unionMemberId, String name, String avatar, String credentialType, String credentialNumber, String telephone, String status, Date birthDate, String gender, String unit, String unions, String dataOrg) {
        // 整理数据
        UserPO userPO = new UserPO();

        userPO.setUnionMemberId(unionMemberId);
        userPO.setName(name);
        userPO.setAvatar(avatar);
        userPO.setCredentialType(credentialType);
        userPO.setCredentialNumber(credentialNumber);
        userPO.setTelephone(telephone);
        userPO.setStatus(status);
        userPO.setBirthDate(birthDate);
        userPO.setGender(gender);
        userPO.setUnit(unit);
        userPO.setUnions(unions);
        userPO.setDataOrg(dataOrg);

        return this.save(userPO);
    }

    @Override
    public UserVO getByUserId(Long id) {
        UserPO userPO = this.getById(id);
        if(null == userPO){
            return null;
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userPO, userVO);
        try {
            String credentialNumber ="";
            String telephone = "";
            if(!StringUtils.isBlank(userPO.getCredentialNumber())) {
                credentialNumber = AESUtils.decrypt(userPO.getCredentialNumber());
            }
            if (!StringUtils.isBlank(userPO.getTelephone())) {
                telephone = AESUtils.decrypt(userPO.getTelephone());
            }
            userVO.setCredentialNumber(credentialNumber);
            userVO.setTelephone(telephone);
        }catch (Exception e){
            logger.info("解密出错 {}", e);
        }

        return userVO;
    }

    @Override
    public boolean updateById(String unionMemberId, String name, String avatar, String credentialType, String credentialNumber, String telephone, String status, Date birthDate, String gender, String unit, String unions, String dataOrg) {
        if(StringUtils.isBlank(unionMemberId)){
            return false;
        }

        String encryptCredentialNumber = "";
        String encryptTelephone = "";
        try {
            if (!StringUtils.isBlank(credentialNumber)) {
                encryptCredentialNumber = AESUtils.encrypt(credentialNumber);
            }
            if (!StringUtils.isBlank(telephone)) {
                encryptTelephone = AESUtils.encrypt(telephone);
            }
        }catch (Exception e){
            logger.info("加密出错 {}", e);
        }
        UpdateWrapper<UserPO> ucenterUserPOUpdateWrapper = new UpdateWrapper<>();

        ucenterUserPOUpdateWrapper.eq("UNION_MEMBER_ID", unionMemberId);

        if (!StringUtils.isBlank(name)) {
            ucenterUserPOUpdateWrapper.set("NAME", name);
        }
        if (!StringUtils.isBlank(avatar)) {
            ucenterUserPOUpdateWrapper.set("AVATER", avatar);
        }
        if (!StringUtils.isBlank(credentialType)) {
            ucenterUserPOUpdateWrapper.set("CREDENTIAL_TYPE", credentialType);
        }
        if (!StringUtils.isBlank(credentialNumber)) {
            ucenterUserPOUpdateWrapper.set("CREDENTIAL_NUMBER", encryptCredentialNumber);
        }
        if (!StringUtils.isBlank(telephone)) {
            ucenterUserPOUpdateWrapper.set("TELEPHONE", encryptTelephone);
        }
        if (!StringUtils.isBlank(status)) {
            ucenterUserPOUpdateWrapper.set("STATUS", status);
        }
        if (null == birthDate) {
            ucenterUserPOUpdateWrapper.set("BIRTH_DATE", birthDate);
        }
        if (!StringUtils.isBlank(gender)) {
            ucenterUserPOUpdateWrapper.set("GENDER", gender);
        }
        if (!StringUtils.isBlank(unit)) {
            ucenterUserPOUpdateWrapper.set("UNIT", unit);
        }
        if (!StringUtils.isBlank(unions)) {
            ucenterUserPOUpdateWrapper.set("UNIONS", unions);
        }
        if (!StringUtils.isBlank(unions)) {
            ucenterUserPOUpdateWrapper.set("DATA_ORG", dataOrg);
        }
        boolean result = this.update(ucenterUserPOUpdateWrapper);

        return result;
    }

    @Override
    public boolean removeById(Long id) {
        return false;
    }

    @Override
    public UserVO getByUnionMemberId(String unionMemberId) {

        if(StringUtils.isBlank(unionMemberId)){
            return null;
        }

        QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
        userPOQueryWrapper.eq("UNION_MEMBER_ID", unionMemberId);

        UserPO userPO = this.getOne(userPOQueryWrapper);

        if(null == userPO){
            return null;
        }

        // 返回数据
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userPO, userVO);

        return userVO;
    }

    @Override
    public String getUserIdsByUnionMemberIds(String unionMemberIds) {
        return null;
    }

    @Override
    public List<Long> getUserIdsByCreatorName(String creatorName) {

        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("NAME", creatorName);
        List<UserPO> userPOList = this.list(queryWrapper);

        if(null == userPOList || userPOList.isEmpty()){
            return null;
        }

        List<Long> idList = userPOList.stream().map(userPO ->  userPO.getId()
        ).collect(Collectors.toList());

        return idList;
    }

    @Override
    public UserVO getUser(Operater operater, String unionMemberIds) throws ParseException {
        return null;
    }
}
